<template>
	<view class="root">
		<view class="fd-row navigation jc-sb">
			<label
				v-for="(tab, index) in tabs"
				:key="index"
				:class="[{ active: index === tabIndex }]"
				@click="switchTab(index)"
			>
				{{ tab }}
			</label>
		</view>
		<view class="mt-50" />

		<scroll-view scroll-y class="f1 oh">
			<block v-for="(item, index) in news" :key="index">
				<navigator
					class="ml-22 mr-22 fd-row"
					:url="`/pages/webview?url=${createWebviewSrc(item.aid)}`"
				>
					<view class="f1 jc-sb">
						<text class="fs-30 color-333 fw-600">{{ item.title }}</text>
						<text class="color-999 fs-24">
							{{ item.addtime | transformTimestampToDate }}
						</text>
					</view>

					<image
						class="bgc-eee br-8 mr-12"
						:style="{ height: `160rpx`, width: `222rpx` }"
						:src="item.img[0]"
						mode="aspectFill"
					/>
				</navigator>
				<view class="height-50" />
			</block>

			<label v-if="!news.length" class="jc-center fs-28">暂无数据</label>
		</scroll-view>
	</view>
</template>

<script>
	import { Storage, formatDate } from "@/static/utils";
	export default {
		data: () => ({
			tabs: ["最新资讯", "通知公告", "新手指南", "关于我们"],
			tabIndex: -1,
			news: [],
		}),
		onLoad() {
			this.switchTab(0);
		},
		filters: {
			transformTimestampToDate(timestamp) {
				return formatDate(+timestamp * 1000, "Y-M-D");
			},
		},
		methods: {
			createWebviewSrc(aid) {
				/**
				 *  fetch(location.origin + "/index.php/" + location.hash.slice(1) + location.search)
				 *	  .then(res => res.json())
				 *	  .then(res => document.write(res.data.content));
				 */

				return encodeURIComponent(
					`http://qkl.xuanhuabang.site/Public/news.html?token=${Storage.get(
						"token"
					)}&aid=${aid}#Home/info/newsdetail`
				);
			},
			switchTab(index) {
				if (this.tabIndex === index) return;
				uni.showToast({ title: "Loading...", icon: "loading" });
				this.tabIndex = index;
				this.news = [];
				this.getData();
			},

			getData() {
				const { $request, news, tabIndex } = this;

				$request.get("/Home/info/news", { type: tabIndex + 1 }).then(({ data }) => {
					uni.hideToast();
					news.push(...data);
				});
			},
		},
	};
</script>
<style>
	page {
		height: 100%;
	}
</style>
<style lang="scss" scoped>
	// scss
	@import "@/static/reset";

	.root {
		height: 100%;
		.navigation {
			padding: 20rpx;
			background-color: #2a62ff;
			font-weight: 500;
			label {
				padding: 12rpx;
				color: #e6e6e6;
				white-space: nowrap;
				font-size: 32rpx;
				&.active {
					color: #fff;
					font-weight: 700;
					font-size: 36rpx;
				}
			}
		}
	}
</style>